package com.neu.controller;

import com.neu.base.Result;
import com.neu.entity.ProjectRsk;
import com.neu.service.impl.ProjectRsfServiceImpl;
import com.neu.utils.riskReader.RiskExcelUtil;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/rsk")
@Tag(name = "风险评估")
public class ProjectRskController {

    @Autowired
    private ProjectRsfServiceImpl projectRsfService;

    @PostMapping("/add")
    @Operation(summary = "添加对某个项目的风险评估")
    public Result addRsk(@RequestBody ProjectRsk projectRsk){
        projectRsk.setRskFactor(
                RiskExcelUtil.calculateRiskFactor(
                    RiskExcelUtil.readExcelFromUrl(projectRsk.getRskUrl())
                ));//计算相应的风险因子

        return Result.success(projectRsfService.save(projectRsk));
    }

    @PostMapping("/update")
    @Operation(summary = "更新风险评估信息")
    public Result updateRsk(@RequestBody ProjectRsk projectRsk){
        projectRsk.setRskFactor(
                RiskExcelUtil.calculateRiskFactor(
                        RiskExcelUtil.readExcelFromUrl(projectRsk.getRskUrl())
                ));//计算相应的风险因子
        projectRsk.setProgress(1);
        Boolean sign = projectRsfService.updateById(projectRsk);
        if(!sign){
            sign = projectRsfService.save(projectRsk);
        }
        return Result.success(sign);
    }

    @GetMapping("/get")
    @Parameter(name = "id", description = "项目ID", required = true)
    @Operation(summary = "获取某个项目的风险评估信息")
    public Result getRskById(@RequestParam String id){
        Map map = new HashMap<>();
        ProjectRsk projectRsk = projectRsfService.getById(id);
        if(projectRsk==null){
            projectRsk = new ProjectRsk();
            projectRsk.setProjectId(id);
            projectRsk.setProgress(0);
            projectRsfService.save(projectRsk);
        }
        map.put("projectId", projectRsk.getProjectId());
        map.put("rskFactor", projectRsk.getRskFactor());
        map.put("rskData", RiskExcelUtil.readExcelFromUrl(projectRsk.getRskUrl()));

        return Result.success(map);
    }


}
